package com.hushan.audio;

import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * 音频采集REST API控制器
 */
@Path("/api/audio")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Slf4j
public class AudioCaptureController {
    
    @Inject
    AudioCaptureManager audioCaptureManager;
    
    @Inject
    FFmpegDeviceDetector ffmpegDeviceDetector;
    
    /**
     * 启动音频采集任务
     * POST /api/audio/capture/start
     */
    @POST
    @Path("/capture/start")
    public Response startCapture(AudioCaptureRequest request) {
        try {
            AudioCaptureTaskInfo taskInfo = audioCaptureManager.startCapture(request);
            log.info("通过API启动音频采集任务: {}", taskInfo.getTaskId());
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "message", "音频采集任务启动成功",
                    "data", taskInfo
                ))
                .build();
                
        } catch (Exception e) {
            log.error("启动音频采集任务失败", e);
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(Map.of(
                    "success", false,
                    "message", "启动音频采集任务失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 停止指定的音频采集任务
     * POST /api/audio/capture/stop/{taskId}
     */
    @POST
    @Path("/capture/stop/{taskId}")
    public Response stopCapture(@PathParam("taskId") String taskId) {
        try {
            boolean success = audioCaptureManager.stopCapture(taskId);
            
            if (success) {
                log.info("通过API停止音频采集任务: {}", taskId);
                return Response.ok()
                    .entity(Map.of(
                        "success", true,
                        "message", "音频采集任务停止成功"
                    ))
                    .build();
            } else {
                return Response.status(Response.Status.NOT_FOUND)
                    .entity(Map.of(
                        "success", false,
                        "message", "未找到指定的音频采集任务: " + taskId
                    ))
                    .build();
            }
            
        } catch (Exception e) {
            log.error("停止音频采集任务失败: {}", taskId, e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "停止音频采集任务失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 停止所有音频采集任务
     * POST /api/audio/capture/stop-all
     */
    @POST
    @Path("/capture/stop-all")
    public Response stopAllCaptures() {
        try {
            audioCaptureManager.stopAllCaptures();
            log.info("通过API停止所有音频采集任务");
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "message", "所有音频采集任务已停止"
                ))
                .build();
                
        } catch (Exception e) {
            log.error("停止所有音频采集任务失败", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "停止所有音频采集任务失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 获取指定任务信息
     * GET /api/audio/capture/task/{taskId}
     */
    @GET
    @Path("/capture/task/{taskId}")
    public Response getTaskInfo(@PathParam("taskId") String taskId) {
        try {
            AudioCaptureTaskInfo taskInfo = audioCaptureManager.getTaskInfo(taskId);
            
            if (taskInfo != null) {
                return Response.ok()
                    .entity(Map.of(
                        "success", true,
                        "data", taskInfo
                    ))
                    .build();
            } else {
                return Response.status(Response.Status.NOT_FOUND)
                    .entity(Map.of(
                        "success", false,
                        "message", "未找到指定的音频采集任务: " + taskId
                    ))
                    .build();
            }
            
        } catch (Exception e) {
            log.error("获取任务信息失败: {}", taskId, e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "获取任务信息失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 获取所有任务信息
     * GET /api/audio/capture/tasks
     */
    @GET
    @Path("/capture/tasks")
    public Response getAllTasksInfo() {
        try {
            List<AudioCaptureTaskInfo> tasks = audioCaptureManager.getAllTasksInfo();
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "data", tasks,
                    "count", tasks.size()
                ))
                .build();
                
        } catch (Exception e) {
            log.error("获取所有任务信息失败", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "获取任务信息失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 获取可用的音频混音器列表
     * GET /api/audio/mixers
     */
    @GET
    @Path("/mixers")
    public Response getAvailableMixers() {
        try {
            List<AudioMixerInfo> mixers = audioCaptureManager.getAvailableMixers();
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "data", mixers,
                    "count", mixers.size()
                ))
                .build();
                
        } catch (Exception e) {
            log.error("获取音频混音器列表失败", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "获取音频混音器列表失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 清理已完成的任务
     * POST /api/audio/capture/cleanup
     */
    @POST
    @Path("/capture/cleanup")
    public Response cleanupCompletedTasks() {
        try {
            int cleanedCount = audioCaptureManager.cleanupCompletedTasks();
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "message", "清理完成",
                    "cleanedCount", cleanedCount
                ))
                .build();
                
        } catch (Exception e) {
            log.error("清理已完成任务失败", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "清理任务失败: " + e.getMessage()
                ))
                .build();
        }
    }
    
    /**
     * 获取服务状态
     * GET /api/audio/status
     */
    @GET
    @Path("/status")
    public Response getServiceStatus() {
        try {
            int activeTaskCount = audioCaptureManager.getActiveTaskCount();
            
            return Response.ok()
                .entity(Map.of(
                    "success", true,
                    "status", "running",
                    "activeTaskCount", activeTaskCount,
                    "timestamp", System.currentTimeMillis()
                ))
                .build();
                
        } catch (Exception e) {
            log.error("获取服务状态失败", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(Map.of(
                    "success", false,
                    "message", "获取服务状态失败: " + e.getMessage()
                ))
                .build();
        }
    }
}